<template>
  <div :style="{ '--dot-width': dotWidth }">
    <div v-if="direction==='horizontal'" class="horizontal-form" :style="{ '--content-width': horizontalContentWidth }">
      <div :class="direction + '-top-space'">
        <div v-for="(item, index) in sortedData" :key="index" :class="direction + '-item'" v-if="item.timestamp!==''">
          <div :class="direction + '-content-top'" :style="{'left': reformData(sortedData)[index].left}" v-if="reformData(sortedData)[index].position==='top'">
            <span class="delay-difference" v-if="needShowTop">{{ item.difference > 0 ? '+' + item.difference : item.difference }} 分钟</span>
            <div>{{ item.content }}</div>
            <div>{{ item.timestamp }}</div>
          </div>
        </div>
      </div>
      <div :class="direction + '-timeline'">
        <div v-for="(item, index) in sortedData" :key="index" :class="direction + '-item'" v-if="item.timestamp!==''">
          <!-- <div :class="direction + '-wrapper'"> -->
            <!-- <div :class="direction + '-content-top'" :style="{'left': reformData(sortedData)[index].left}" v-if="reformData(sortedData)[index].position==='top'">
              <span class="delay-difference" v-if="typeof(item.difference)!=='undefined'">{{ item.difference > 0 ? '+' + item.difference : item.difference }} 分钟</span>
              <div>{{ item.content }}</div>
              <div>{{ item.timestamp }}</div>
            </div> -->
            <div :class="direction + '-dotline'">
              <div :style="{'width': dotWidth, 'height': dotWidth, 'borderRadius': parseInt(dotWidth) / 2 + 'px', 'background': dotColor}"></div>
              <div :class="direction + '-line'" v-if="index < (sortedData.length - 1)" :style="{'width': getActivityLineWidth(sortedData[index].timestamp, sortedData[index+1].timestamp, index), 'height': lineHeight, 'background': lineColor}"></div>
            </div>
            <!-- <div :class="direction + '-content'" :style="{'left': reformData(sortedData)[index].left}" v-if="reformData(sortedData)[index].position==='bottom'">
              <div>{{ item.content }}</div>
              <div>{{ item.timestamp }}</div>
            </div> -->
          <!-- </div> -->
        </div>
      </div>
    </div>
    <div v-else>
      <div :class="direction + '-timeline'" :style="{'width': maxWidth ? maxWidth : 'unset',}">
        <div v-for="(item, index) in sortedData" :key="index" :class="direction + '-item'">
          <div :class="direction + '-wrapper'">
            <div :class="direction + '-dotline'">
              <div :style="{'width': dotWidth, 'height': dotWidth, 'borderRadius': parseInt(dotWidth) / 2 + 'px', 'background': item.timestamp==='' ? '#aaa' : dotColor}"></div>
              <div :class="direction + '-line'" v-if="index < (sortedData.length - 1)" :style="{'background': item.timestamp==='' || (index<(sortedData.length-1) && sortedData[index + 1] && sortedData[index + 1].timestamp==='') ? '#aaa' :lineColor, 'height': lineHeight, 'width': lineWidth}"></div>
            </div>
            <div :class="direction + '-content'" >
              <div class="content">{{ item.content }}</div>
              <div>{{ item.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "RichTimeline",
  props: {
    direction:{
      type: String,
      default: 'vertical', // vertical 和 horizontal
    },
    horizontalContentWidth: {
      type: String,
      default: '130px',
    },
    lineStyle:{
      type: String,
      default: '',
    },
    lineColor:{
      type: String,
      default: '#0D48CE',
    },
    lineHeight:{
      type: String,
      default: '1px', // 横向时间线时用于设置横线的粗细；竖向时间线时用于设置线条的高度
    },
    lineWidth: {
      type: String,
      default: '1px', // 竖向时间线此配置有效，用于设置线条的粗细
    },
    dotColor: {
      type: String,
      default: '#0D48CE',
    },
    dotWidth: {
      type: String,
      default: '20px',
    },
    maxWidth: {
      type: String,
      default: '',
    },
    maxHeight: {
      type: String,
      default: '',
    },
    divideType: {
      type: String,
      default: 'even', // 时间线各节点分部方式，even 是均分宽度（高度）, time 按时间计算各自长度, 未来可扩展开发其他类型
    },
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      lastActivityLeft: 'unset',
      fullLineDotsWidth: 0,
    };
  },
  computed: {
    sortedData() {
      let data = [];

      if (this.direction==='horizontal') {
        data = this.sortTimings(this.data);
        console.log('now da:', JSON.stringify(data))
        data = data.filter(item => item.timestamp!== '');
      } else {
        data = this.data;
      }

      data = [{"key":"eventTime","content":"事件发生时间","timestamp":"2023-12-21 00:00:00"},{"key":"arrivalTimeOut","content":"抵达现场时限","timestamp":"2023-12-21 05:20:00"},{"key":"arrivalTime","content":"实际抵达时间","timestamp":"2023-12-21 05:40:00"},{"key":"outOfTrapTimeOut","content":"人员脱困时限","timestamp":"2023-12-21 08:20:00"},{"key":"getoutTime","content":"实际脱困时间","timestamp":"2023-12-21 12:20:00"}];

      return data;
    },
  },
  watch: {
  },
  created() {
  },
  mounted() {
    // console.log('now offsetWidth:', document.querySelector('.dialog-body').offsetWidth);
  },
  methods: {
    needShowTop(item) {
      return typeof(item.difference)!=='undefined'
    },
    sortTimings(arr) {
      function compareTimestamps(a, b) {
        return new Date(a.timestamp) - new Date(b.timestamp);
      }

      arr.sort(compareTimestamps);

      return arr;
    },
    calculateWholeTimeDifferenceInMinutes(sortedTimes) {
      if (sortedTimes.length === 0) {
        return 0;
      }

      const firstTimestamp = new Date(sortedTimes[0].timestamp);
      const lastTimestamp = new Date(sortedTimes[sortedTimes.length - 1].timestamp);

      const timeDifferenceInMilliseconds = lastTimestamp - firstTimestamp;
      const timeDifferenceInMinutes = timeDifferenceInMilliseconds / (1000 * 60);

      return timeDifferenceInMinutes;
    },
    getMinuteWidth() {
      const bodyWidth = document.querySelector('.dialog-body').offsetWidth;
      const fullLineDotsWidth = bodyWidth - parseInt(this.horizontalContentWidth) - parseInt(this.dotWidth);
      let dots = [];

      this.fullLineDotsWidth = fullLineDotsWidth;
      this.sortedData.filter(item => item.timestamp!=='').forEach(element => {
        if (!dots.includes(element.timestamp)) {
          dots.push(element.timestamp);
        }
      });
      const fullLineWidth = fullLineDotsWidth - ((dots.length > 2) ? (dots.length - 2) : 0) * parseInt(this.dotWidth);
      const minuteWidth = fullLineWidth / this.calculateWholeTimeDifferenceInMinutes(this.sortedData.filter(item => item.timestamp!==''))

      return minuteWidth;
    },
    calculateTwoTimeInMinutes(strTime1, strTime2) {
      const firstTimestamp = new Date(strTime1);
      const lastTimestamp = new Date(strTime2);

      const timeDifferenceInMilliseconds = lastTimestamp - firstTimestamp;
      const timeDifferenceInMinutes = timeDifferenceInMilliseconds / (1000 * 60);

      return timeDifferenceInMinutes;
    },
    reformData(sortedTimes) {
      sortedTimes = sortedTimes.filter(item => item.timestamp!=='');

      const paddingLeft = (document.querySelector('.wrapper .dialog .body').offsetWidth - document.querySelector('.dialog-body').offsetWidth) / 2;

      let arr = [];

      for (let i=0; i<sortedTimes.length; i++) {
        if (i === 0) {
          arr.push(Object.assign({}, sortedTimes[i], { left: paddingLeft + parseInt(this.dotWidth) / 2 + 'px'}, { position: sortedTimes[i].content.includes('实际') ? 'top' : 'bottom' }))
        } else {
          let uniqDots = [];

          for (let j=0; j<i+1; j++) {
            if (!uniqDots.includes(sortedTimes[j])) {
              uniqDots.push(sortedTimes[j]);
            }
          }

          arr.push(Object.assign({},
            sortedTimes[i],
            { left: paddingLeft + (parseInt(this.dotWidth) * (uniqDots.length) - parseInt(this.dotWidth) / 2) + parseInt(this.calculateTwoTimeInMinutes(sortedTimes[0].timestamp, sortedTimes[i].timestamp) * this.getMinuteWidth()) + 'px' },
            { position: sortedTimes[i].content.includes('实际') ? 'top' : 'bottom' },
          ))
        }
      }

      return arr;
    },
    getActivityLineWidth(strTime1, strTime2, timeIndex) {
      let index = timeIndex + 1;
      console.log('index:', index);
      // console.log('left:', document.querySelector('.horizontal-timeline > .horizontal-item').clientLeft);
      // console.log('minWidth:', parseInt(this.getMinuteWidth()));
      // console.log(strTime1, strTime2,'minutes:', this.calculateTwoTimeInMinutes(strTime1, strTime2) ,' width:', parseInt(this.calculateTwoTimeInMinutes(strTime1, strTime2) * this.getMinuteWidth()) + 'px')
      if (timeIndex === 0) {
        this.sortedData[0]['absoluteLeft'] = parseInt(parseInt(this.horizontalContentWidth) / 2);
        this.sortedData[0]['marginLeft'] = 0;
      }

      // let allLeft = 0;

      // for (let i=0; i < index; i++) {
      //   allLeft = this.sortedData[i]['left'] + allLeft + parseInt(this.dotWidth);
      // }

      // console.log('allleft:', allLeft);
      // console.log('timediff:', parseInt(this.calculateTwoTimeInMinutes(strTime1, strTime2) * this.getMinuteWidth()));

      this.sortedData[index]['absoluteLeft']= parseInt(this.calculateTwoTimeInMinutes(strTime1, strTime2) * this.getMinuteWidth()) + this.sortedData[index - 1]['left'] + parseInt(this.dotWidth);
      this.sortedData[index]['marginLeft'] = parseInt(this.calculateTwoTimeInMinutes(strTime1, strTime2) * this.getMinuteWidth()) - parseInt(this.horizontalContentWidth);
      console.log('final sso:', this.sortedData);

      return parseInt(this.calculateTwoTimeInMinutes(strTime1, strTime2) * this.getMinuteWidth()) + 'px';
    },
  },
};
</script>
<style lang="scss" scoped>
.vertical-timeline {
  margin-bottom: 30px;

  .vertical-item {
    .vertical-wrapper {
      display: flex;
      flex-direction: row;
      .vertical-dotline {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      .vertical-content {
        margin-left: 10px;
        display: flex;
        flex-direction: row;
        height: var(--dot-width);
        line-height: var(--dot-width);

        .content {
          width: 150px;
          overflow: hidden;
        }
      }
    }
  }
}

.horizontal-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;

  .horizontal-top-space {
    display: flex;
    flex-direction: row;
    width: 100%;
    background:yellow;
    justify-content: flex-start;
    align-items: center;

    .horizontal-item {

    }
  }

  .horizontal-timeline {
    display: flex;
    flex-direction: row;
    width: 100%;
    background:pink;
    justify-content: center;
    align-items: center;

    .horizontal-item {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .horizontal-dotline {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
      }

    }
    // margin-bottom: 30px;

        // .horizontal-dotline {
        //   display: flex;
        //   flex-direction: row;
        //   align-items: center;
        //   margin-top: 58px;
        //   margin-bottom: 6px;
        //   // position: relative;
        //   // left: calc(var(--content-width) / 2 - 10px);
        // }
        // .horizontal-content, .horizontal-content-top {
        //   // position: absolute;
        //   width: var(--content-width);
        //   text-align: center;
        // }

    // .horizontal-item {
    //   .horizontal-wrapper {
    //     .horizontal-dotline {
    //       display: flex;
    //       flex-direction: row;
    //       align-items: center;
    //       margin-top: 58px;
    //       margin-bottom: 6px;
    //       // position: relative;
    //       // left: calc(var(--content-width) / 2 - 10px);
    //     }
    //     .horizontal-content, .horizontal-content-top {
    //       // position: absolute;
    //       width: var(--content-width);
    //       text-align: center;
    //     }

    //     .horizontal-content-top {
    //       top: 70px;

    //       .delay-difference {
    //         background: #FBDBDA;
    //         color: #DC0000;
    //         padding: 2px 4px;
    //         border-radius: 8px;
    //         margin-bottom: 4px;
    //         display: inline-block;
    //       }
    //     }
    //   }
    // }
  }
}
</style>
